package com.gzsc_tech.modules.wx.handler;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzsc_tech.modules.wx.entity.CustManager;
import com.gzsc_tech.modules.wx.service.CustManagerService;
import com.gzsc_tech.modules.wx.service.MsgReplyService;
import com.gzsc_tech.modules.wx.service.WxUserService;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.util.StringUtils;

/**
 * @author Binary Wang
 */
@Component
public class SubscribeHandler extends AbstractHandler {
    @Autowired
    MsgReplyService msgReplyService;
    @Autowired
    WxUserService userService;

    @Autowired
    CustManagerService custManagerService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser() + "，事件：" + wxMessage.getEventKey());
        String appid = WxMpConfigStorageHolder.get();
        this.logger.info("appid:{}",appid);
        userService.refreshUserInfo(wxMessage.getFromUser(),appid);

//        msgReplyService.tryAutoReply(appid, true, wxMessage.getFromUser(), wxMessage.getEvent());
        /**
         *leeEsun改造代码
         */
        String originalKey = wxMessage.getEventKey();
        String[] splitKey = originalKey.split("_");
        String trueEventKey = splitKey[1];
        this.logger.info("trueEventKey为：{}", trueEventKey);
        this.logger.info("当前的eventKey是：{}", wxMessage.getEventKey());
        if (StringUtils.hasText(wxMessage.getEventKey())) {// 处理特殊事件，如用户扫描带参二维码关注
//            msgReplyService.tryAutoReply(appid, true, wxMessage.getFromUser(), wxMessage.getEventKey());
            msgReplyService.tryAutoReply(appid, true, wxMessage.getFromUser(), trueEventKey);
            //根据对应场景值给客户经理算业绩,先查询是否已有此客户经理，如果没有则直接插入，否则更新count值
            QueryWrapper<CustManager> custManagerQueryWrapper = new QueryWrapper<>();
            custManagerQueryWrapper.eq("manager_app_id", trueEventKey);
            CustManager manager = custManagerService.getOne(custManagerQueryWrapper);
            this.logger.info("此时客户经理的数据为：{}", manager);
            if(manager != null) {
                Integer inviteCount = manager.getManagerInviteCount();
                inviteCount += 1;
                manager.setManagerInviteCount(inviteCount);
                custManagerService.update(manager,custManagerQueryWrapper);
            } else {
                CustManager custManager = new CustManager();
                custManager.setManagerAppId(trueEventKey);
                custManager.setManagerInviteCount(1);
                custManagerService.save(custManager);
            }
        }
        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    protected WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) {
        this.logger.info("特殊请求-新关注用户 OPENID: " + wxMessage.getFromUser());
        //对关注事件和扫码事件分别处理
        String appid = WxMpConfigStorageHolder.get();
        userService.refreshUserInfo(wxMessage.getFromUser(),appid);
        msgReplyService.tryAutoReply(appid, true, wxMessage.getFromUser(), wxMessage.getEvent());
        if (StringUtils.hasText(wxMessage.getEventKey())) {
            msgReplyService.tryAutoReply(appid, true, wxMessage.getFromUser(), wxMessage.getEventKey());
        }
        return null;
    }

}
